package App.Controller;

import App.Model.Contact_Message;
import App.Model.UserData;
import App.Public.Lib.CopyFileUtil;
import App.Public.controller;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.geometry.Pos;
import javafx.scene.Node;
import javafx.scene.control.*;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.FlowPane;
import javafx.scene.layout.Pane;
import javafx.scene.layout.VBox;
import javafx.scene.text.Font;
import javafx.stage.FileChooser;
import javafx.stage.Stage;

import java.io.File;
import java.net.URL;
import java.util.ResourceBundle;

public class AddContactController extends controller implements Initializable
{

    @FXML public VBox rootPane;
    @FXML public TextField text_GivenName;
    @FXML public TextField text_FirstName;
    @FXML public TextField text_PhoneNumber;
    @FXML public TextField text_Email;
    @FXML public TextArea text_Remark;
    @FXML public TextField text_Birthday;
    @FXML public TextField text_QQ;
    @FXML public TextField text_PetName;
    @FXML public TextField text_Website;
    @FXML public TextField text_Country_Home;
    @FXML public TextField text_Province_Home;
    @FXML public TextField text_PostCode_Company;
    @FXML public TextField text_Street_Company;
    @FXML public TextField text_City_Company;
    @FXML public TextField text_Province_Company;
    @FXML public TextField text_Country_Company;
    @FXML public TextField text_Fax;
    @FXML public TextField text_Job;
    @FXML public TextField text_Department;
    @FXML public TextField text_Company;
    @FXML public TextField text_PostCode_Home;
    @FXML public TextField text_Street_Home;
    @FXML public TextField text_City_Home;
    @FXML public Label label_showName;
    @FXML public ComboBox comboBox_Sex;
    @FXML public ImageView picture_Contact;
    @FXML public Button button_Cancel;
    @FXML public Button button_AddPhone;
    @FXML public VBox vBox_Phone;
    @FXML public VBox vBox_Email;
    @FXML public VBox vBox_All;
    @FXML public AnchorPane anchorPane_Up;
    //现在登录的用户
    private UserData user=(UserData)DATA.getData("userData");

    //group和username在mainViewController里调用Contact_Message的含参构造器时set了↓↓↓↓↓
    private Contact_Message contactNow = (Contact_Message)(controller.DATA.getData("ContactNow"));

    public AddContactController() throws Exception {}

    @Override
    public void initialize(URL url, ResourceBundle rb) {
        loadCss(rootPane,"AddContact.css");
        picture_Contact.setImage(new Image(String.valueOf(getResource("Image/Contacts_icon.png"))));

        text_GivenName.textProperty().addListener( (event)->{
            label_showName.setText("显示名字为："+text_GivenName.getText()+text_FirstName.getText());
        });

        text_FirstName.textProperty().addListener( (event)->{
            label_showName.setText("显示名字为："+text_GivenName.getText()+text_FirstName.getText());
        });

//        ArrayList<Window> windowList = null;
//        try {
//            windowList = (ArrayList<Window>) controller.DATA.getData("windowList");
//        } catch (Exception e) {}
//        windowList.add(vBox_All.getScene().getWindow());
    }

    public void cancelAction(ActionEvent actionEvent){
        button_Cancel.getScene().getWindow().hide();     //关闭窗口(learning)
    }

    public void addPicture(ActionEvent actionEvent) throws Exception
    {
        FileChooser fileChooser = new FileChooser();
        configureFileChooser(fileChooser);
        File file = fileChooser.showOpenDialog(new Stage());

        if (file != null)
        {
            String imageName=file.getName();
            String imagePath=user.getUserPath()+"image/"+imageName;
            if(CopyFileUtil.copyFile(file.getAbsolutePath(),imagePath,true)) {
                contactNow.setPicture(new File(imagePath).toURI());
            }
            else {
                contactNow.setPicture(file.toURI());
            }

            picture_Contact.setImage(new Image(file.toURI().toString()));
        }
    }

    private static void configureFileChooser(final FileChooser fileChooser) {
        fileChooser.setTitle("View Pictures");
        fileChooser.setInitialDirectory(
                new File(System.getProperty("user.home"))
        );
        fileChooser.getExtensionFilters().clear();
        fileChooser.getExtensionFilters().addAll(
                new FileChooser.ExtensionFilter("JPG", "*.jpg"),
                new FileChooser.ExtensionFilter("PNG", "*.png")
        );
    }

    public void saveAction(ActionEvent actionEvent) throws Exception {
        if (saveContact() != null)
            cancelAction(new ActionEvent());
    }

    public Contact_Message saveContact() throws Exception{
        String textName = text_GivenName.getText() + text_FirstName.getText();
        textName = textName.replaceAll(" ","");
        if (textName.length() == 0){
            Alert alert = new Alert(Alert.AlertType.WARNING);
            alert.setTitle("Warning");
            alert.setHeaderText(null);
            alert.setContentText("未输入姓名！");
            alert.showAndWait();
            return null;
        }

        contactNow.setGiveName(text_GivenName.getText());
        contactNow.setFirstName(text_FirstName.getText());
        contactNow.setFullName(text_GivenName.getText() + text_FirstName.getText());
        //Add Phone
        for (Node flowPaneIncludePhoneText : vBox_Phone.getChildren()) {
            FlowPane panel = (FlowPane)flowPaneIncludePhoneText;
            for(Node control : panel.getChildren()){
                if (control instanceof TextField && !((TextField) control).getText().equals("")){
                    contactNow.addPhoneNumber((((TextField) control).getText()));
                }
            }
        }

        for (Node flowPaneIncludeEmailText : vBox_Email.getChildren()) {
            FlowPane panel = (FlowPane)flowPaneIncludeEmailText;
            for(Node control : panel.getChildren()){
                if (control instanceof TextField && !((TextField) control).getText().equals("")){
                    contactNow.addEmail((((TextField) control).getText()));
                }
            }
        }

        contactNow.setRemark(text_Remark.getText());
        if (comboBox_Sex.getSelectionModel().getSelectedItem() != null) {
            contactNow.setSex(comboBox_Sex.getSelectionModel().getSelectedItem().toString());
        }
        contactNow.setBirthday(text_Birthday.getText());
        contactNow.setPetName(text_PetName.getText());
        contactNow.setQQ(text_QQ.getText());
        contactNow.setWebsite(text_Website.getText());
        contactNow.setCountry_Home(text_Country_Home.getText());
        contactNow.setProvince_Home(text_Province_Home.getText());
        contactNow.setPostCode_Home(text_PostCode_Home.getText());
        contactNow.setStreet_Home(text_Street_Home.getText());
        contactNow.setCity_Home(text_City_Home.getText());
        contactNow.setProvince_Company(text_Province_Company.getText());
        contactNow.setCompany(text_Company.getText());
        contactNow.setCity_Company(text_City_Company.getText());
        contactNow.setCountry_Company(text_Country_Company.getText());
        contactNow.setStreet_Company(text_Street_Company.getText());
        //picture在addPicture监听器里set

        /*
        更新联系人数据表和表格数据
         */
        UserData userNow = (UserData) (controller.DATA.getData("userData"));
        userNow.addPerson(contactNow);

        //ListView<String> contactList = (ListView) (controller.DATA.getData("contactList"));
        //contactList.getSelectionModel().selectFirst();
        MainController mainController=(MainController) (controller.DATA.getData("mainController"));
        mainController.refresh();
        return contactNow;
    }

    public void addPhoneAction(ActionEvent actionEvent) throws Exception {
        vBox_Phone.getChildren().add(new PhoneAddPanel());
    }

    public void addEmailAction(ActionEvent actionEvent) throws Exception {
        vBox_Email.getChildren().add(new PhoneAddPanel());
    }

    class PhoneAddPanel extends FlowPane {

        public PhoneAddPanel() throws Exception {
            vBox_All.setPrefHeight(vBox_All.getPrefHeight() + 26.0);
            setAlignment(Pos.CENTER);
            TextField text_Phone = new TextField();
            Pane panel = new Pane();
            panel.setPrefHeight(33.0);
            panel.setPrefWidth(42.0);
            text_Phone.setPrefWidth(299.0);
            text_Phone.setPrefHeight(23.0);
            text_Phone.setFont(new Font("system",12));
            this.getChildren().add(panel);
            this.getChildren().add(text_Phone);
        }
    }
}

